﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Animoso.Domain;
using Animoso.Domain.Data;
using NHibernate;
using NHibernate.Criterion;

namespace Animoso.Data
{
    public class SponsorRepository : BaseRepository<Sponsor>, ISponsorRepository
    {
        public IEnumerable<Sponsor> GetSponsorsByImageLocation(ImageLocation imageLocation)
        {
            using (ISession session = SessionProvider.GetSession())
            {
                return session.CreateCriteria<Sponsor>()
                    .Add(Expression.Eq("ImageLocation", imageLocation))
                    .Add(Expression.Eq("Active", true))
                    .List<Sponsor>();
            }
        }

        public Sponsor GetSponsorByImageLocation(ImageLocation imageLocation)
        {
            using(ISession session = SessionProvider.GetSession())
            {
                Sponsor sponsor = session.CreateCriteria<Sponsor>()
                    .Add(Expression.Eq("ImageLocation", imageLocation))
                    .Add(Expression.Eq("Active", true))
                    .UniqueResult<Sponsor>();
                return sponsor;
            }
        }

        public void DeleteInactive()
        {
            using (ISession session = SessionProvider.GetSession())
            {
                using(ITransaction transaction = session.BeginTransaction())
                {
                    IList<Sponsor> sponsors = session.CreateCriteria<Sponsor>()
                        .Add(Expression.Eq("Active", false))
                        .List<Sponsor>();
                    foreach (var sponsor in sponsors)
                    {
                        session.Delete(sponsor);
                    }
                    transaction.Commit();
                }
            }
        }
    }
}
